<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>字符串常量池在1.6与1.8以及String、StringBuffer、StringBuilder | Eetal&#39;s Blog</title>

  <!-- keywords -->
  

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="欢迎查看Eetal的第十八篇博客–字符串常量池在1.6与1.8以及String、StringBuffer、StringBuilder 字符串加入常量池时机直接使用双引号声明出来的String对象会直接存储在常量池中，相同字符串使用同一个对象而使用构造函数创建的会新创建一个字符串对象，但是该字符串对象的字符数组value会引用常量池中的字符串对象的字符数组使用String的concat方法拼接后的字">
<meta property="og:type" content="article">
<meta property="og:title" content="字符串常量池在1.6与1.8以及String、StringBuffer、StringBuilder">
<meta property="og:url" content="http://eetal.gitee.io/blog/2019/04/12/字符串常量池在1.6与1.8以及String、StringBuffer、StringBuilder/index.html">
<meta property="og:site_name" content="Eetal&#39;s Blog">
<meta property="og:description" content="欢迎查看Eetal的第十八篇博客–字符串常量池在1.6与1.8以及String、StringBuffer、StringBuilder 字符串加入常量池时机直接使用双引号声明出来的String对象会直接存储在常量池中，相同字符串使用同一个对象而使用构造函数创建的会新创建一个字符串对象，但是该字符串对象的字符数组value会引用常量池中的字符串对象的字符数组使用String的concat方法拼接后的字">
<meta property="og:locale" content="default">
<meta property="og:image" content="http://eetal.gitee.io/blog/images/string/jdk1.6.jpg">
<meta property="og:image" content="http://eetal.gitee.io/blog/images/string/jdk1.8.jpg">
<meta property="og:updated_time" content="2019-04-14T20:26:31.643Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="字符串常量池在1.6与1.8以及String、StringBuffer、StringBuilder">
<meta name="twitter:description" content="欢迎查看Eetal的第十八篇博客–字符串常量池在1.6与1.8以及String、StringBuffer、StringBuilder 字符串加入常量池时机直接使用双引号声明出来的String对象会直接存储在常量池中，相同字符串使用同一个对象而使用构造函数创建的会新创建一个字符串对象，但是该字符串对象的字符数组value会引用常量池中的字符串对象的字符数组使用String的concat方法拼接后的字">
<meta name="twitter:image" content="http://eetal.gitee.io/blog/images/string/jdk1.6.jpg">
  
    <link rel="alternative" href="/atom.xml" title="Eetal&#39;s Blog" type="application/atom+xml">
  
  
    <link rel="icon" href="http://www.yangyitao.top/FiveChess/resource/ico/favicon.ico">
  
  <link rel="stylesheet" href="/blog/css/style.css">
  
  

  <script src="//cdn.bootcss.com/require.js/2.3.2/require.min.js"></script>
  <script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>

  
</head>
<body>
  <div id="container">
    <div id="particles-js"></div>
    <div class="left-col">
    <div class="overlay"></div>
<div class="intrude-less">
	<header id="header" class="inner">
		<a href="/" class="profilepic">
			
			<img lazy-src="/blog/images/head.jpg" class="js-avatar">
			
		</a>

		<hgroup>
		  <h1 class="header-author"><a href="/">Eetal</a></h1>
		</hgroup>

		
		<p class="header-subtitle">java coder</p>
		

		
			<div class="switch-btn">
				<div class="icon">
					<div class="icon-ctn">
						<div class="icon-wrap icon-house" data-idx="0">
							<div class="birdhouse"></div>
							<div class="birdhouse_holes"></div>
						</div>
						<div class="icon-wrap icon-ribbon hide" data-idx="1">
							<div class="ribbon"></div>
						</div>
						
						<div class="icon-wrap icon-link hide" data-idx="2">
							<div class="loopback_l"></div>
							<div class="loopback_r"></div>
						</div>
						
						
					</div>
					
				</div>
				<div class="tips-box hide">
					<div class="tips-arrow"></div>
					<ul class="tips-inner">
						<li>菜单</li>
						<li>标签</li>
						
						<li>友情链接</li>
						
						
					</ul>
				</div>
			</div>
		

		<div class="switch-area">
			<div class="switch-wrap">
				<section class="switch-part switch-part1">
					<nav class="header-menu">
						<ul>
						
							<li><a href="/blog/">Home</a></li>
				        
							<li><a href="/blog/archives">Archives</a></li>
				        
						</ul>
					</nav>
					<nav class="header-nav">
						<div class="social">
							
						</div>
					</nav>
				</section>
				
				
				<section class="switch-part switch-part2">
					<div class="widget tagcloud" id="js-tagcloud">
						
					</div>
				</section>
				
				
				
				<section class="switch-part switch-part3">
					<div id="js-friends">
					
			          <a target="_blank" class="main-nav-link switch-friends-link" href="https://github.com/smackgg/hexo-theme-smackdown">smackdown</a>
			        
			        </div>
				</section>
				

				
			</div>
		</div>
	</header>				
</div>
    </div>
    <div class="mid-col">
      <nav id="mobile-nav">
  	<div class="overlay">
  		<div class="slider-trigger"></div>
  		<h1 class="header-author js-mobile-header hide">Eetal</h1>
  	</div>
	<div class="intrude-less">
		<header id="header" class="inner">
			<div class="profilepic">
				<img lazy-src="/blog/images/head.jpg" class="js-avatar">
			</div>
			<hgroup>
			  <h1 class="header-author">Eetal</h1>
			</hgroup>
			
			<p class="header-subtitle">java coder</p>
			
			<nav class="header-menu">
				<ul>
				
					<li><a href="/blog/">Home</a></li>
		        
					<li><a href="/blog/archives">Archives</a></li>
		        
		        <div class="clearfix"></div>
				</ul>
			</nav>
			<nav class="header-nav">
				<div class="social">
					
				</div>
			</nav>
		</header>				
	</div>
</nav>
      <div class="body-wrap"><article id="post-字符串常量池在1.6与1.8以及String、StringBuffer、StringBuilder" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a href="/blog/2019/04/12/字符串常量池在1.6与1.8以及String、StringBuffer、StringBuilder/" class="article-date">
  	<time datetime="2019-04-12T03:09:49.400Z" itemprop="datePublished">2019-04-12</time>
</a>
    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      字符串常量池在1.6与1.8以及String、StringBuffer、StringBuilder
      
    </h1>
  

      </header>
      
      <div class="article-info article-info-post">
        
        

        
        <div class="clearfix"></div>
      </div>
      
    
    <div class="article-entry" itemprop="articleBody">
      
        <p>欢迎查看Eetal的第十八篇博客–字符串常量池在1.6与1.8以及String、StringBuffer、StringBuilder</p>
<h2 id="字符串加入常量池时机"><a href="#字符串加入常量池时机" class="headerlink" title="字符串加入常量池时机"></a>字符串加入常量池时机</h2><p>直接使用双引号声明出来的String对象会直接存储在常量池中，相同字符串使用同一个对象<br>而使用构造函数创建的会新创建一个字符串对象，但是该字符串对象的字符数组value会引用常量池中的字符串对象的字符数组<br>使用String的concat方法拼接后的字符串使用的是share模式的构造函数进行构造，默认不会引用常量池（此处的share模式有点threadLocal的那种意思，所以是创建副本不去引用常量池）<br>对于不进入常量池而常量池中没有的字符串，可以显示调用String的intern方法将其加入常量池<br>引用自博客<a href="https://blog.csdn.net/chen1280436393/article/details/51768609" target="_blank" rel="noopener">https://blog.csdn.net/chen1280436393/article/details/51768609</a><br>也就是说，代码里双引号直接包含的字符串会被放进常量池<br>比如<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">String str1 = <span class="string">"我爱java"</span>;//我爱java进入常量池</span><br><span class="line">String str2 = <span class="string">"歪歪"</span>+<span class="string">"梯"</span>;//因为编译器会优化，所以等价于<span class="string">"歪歪梯"</span>，歪歪梯会放入常量池</span><br><span class="line">String str3 = new String(<span class="string">"构造1"</span>);//构造1会放入常量池</span><br><span class="line">String str4 = new String(<span class="string">"构造2"</span>)+<span class="string">"测试"</span>;//构造2会放入常量池。测试会放入常量池</span><br><span class="line">String str5 = new String(<span class="string">"构造3"</span>)+new String(<span class="string">"构造4"</span>);//构造3会放入常量池。构造4会放入常量池</span><br><span class="line">/*</span><br><span class="line">*最终常量池包括 我爱java 歪歪梯 构造1 构造2 构造3 构造4 测试 7个字符串</span><br><span class="line">*注意非字面常量字符串拼接的结果字符串默认并不会加入常量池（因此也不会默认去引用常量池，这个下面会验证）</span><br><span class="line">*/</span><br></pre></td></tr></table></figure></p>
<p>如果是直接使用常量字符串赋值的，会直接引用常量池该字符串对象<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">String str = &quot;123&quot;;</span><br><span class="line">String str2 = &quot;1&quot;+&quot;23&quot;;</span><br><span class="line">System.out.println(str == str2);//true</span><br></pre></td></tr></table></figure></p>
<p>要将非字面常量字符串存储进常量池，可以调用字符串对象的intern方法<br>为什么只存储字面常量，其实也不难理解，jvm虚拟机显示存储字面常量是因为字面常量是直接出现在代码里的，是确定，的同时也是一定会用到的，而且有很大概率用来进行多次拼接（循环体代码），所以放进常量池优化内存</p>
<h2 id="jdk1-6-与-jdk1-8的String和常量池"><a href="#jdk1-6-与-jdk1-8的String和常量池" class="headerlink" title="jdk1.6 与 jdk1.8的String和常量池"></a>jdk1.6 与 jdk1.8的String和常量池</h2><p>jdk1.6使用（方法区）永久代存储类的静态信息和运行时常量池，字符串常量池也在其中，因为常量池不在堆内存，只有触发fullgc才会回收常量池中对象</p>
<h3 id="jdk1-6字符串常量池内存示意图"><a href="#jdk1-6字符串常量池内存示意图" class="headerlink" title="jdk1.6字符串常量池内存示意图"></a>jdk1.6字符串常量池内存示意图</h3><p><img src="/blog/images/string/jdk1.6.jpg" alt="jdk1.6字符串常量池内存示意图"></p>
<h3 id="jdk1-8字符串常量池内存示意图"><a href="#jdk1-8字符串常量池内存示意图" class="headerlink" title="jdk1.8字符串常量池内存示意图"></a>jdk1.8字符串常量池内存示意图</h3><p>jdk1.8字符串常量池移到元数据，元数据在本地内存，同时字符串加入常量池行为发生变化<br><img src="/blog/images/string/jdk1.8.jpg" alt="jdk1.8字符串常量池内存示意图"><br>jdk1.6在调用intern时，如果常量池没有执行的操作是复制字符串在常量池创建一个字符串对象，并返回该对象<br>jdk1.8在调用intern时，如果常量池没有则在常量池创建一个字符串引用，引用当前字符串对象，返回this<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">String str1 = new StringBuilder(<span class="string">"hello"</span>).append(<span class="string">"java"</span>).toString();</span><br><span class="line">String str2 = new StringBuilder(<span class="string">"hello"</span>).append(<span class="string">"java"</span>).toString();</span><br><span class="line">//此时常量池只有两个字符串hello和java</span><br><span class="line"></span><br><span class="line">//jdk1.6的测试效果</span><br><span class="line">System.out.println(str1.intern()==str1);//<span class="literal">false</span></span><br><span class="line">System.out.println(str2==str2.intern());//<span class="literal">false</span></span><br><span class="line"></span><br><span class="line">//jdk1.8的测试效果</span><br><span class="line">System.out.println(str1.intern()==str1);//<span class="literal">true</span></span><br><span class="line">System.out.println(str2==str2.intern());//<span class="literal">false</span></span><br></pre></td></tr></table></figure></p>
<h2 id="使用jol工具进行验证"><a href="#使用jol工具进行验证" class="headerlink" title="使用jol工具进行验证"></a>使用jol工具进行验证</h2><h3 id="验证代码"><a href="#验证代码" class="headerlink" title="验证代码"></a>验证代码</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line">String str1 = new StringBuilder(<span class="string">"hello"</span>).append(<span class="string">"java"</span>).toString();</span><br><span class="line">String str2 = new StringBuilder(<span class="string">"hello"</span>).append(<span class="string">"java"</span>).toString();</span><br><span class="line"></span><br><span class="line">System.out.println(str1.intern()==str1);</span><br><span class="line">System.out.println(str2==str2.intern());</span><br><span class="line"></span><br><span class="line">System.out.println(<span class="string">"use jol check ..."</span>);</span><br><span class="line"></span><br><span class="line">String builderString = new StringBuilder(<span class="string">"faker"</span>).append(<span class="string">"大魔王"</span>).toString();</span><br><span class="line">System.out.println(<span class="string">"-------------------------------------------------------------------------------------------------------"</span>);</span><br><span class="line">System.out.println(<span class="string">"builderString info"</span>);</span><br><span class="line">System.out.println(GraphLayout.parseInstance(builderString).toPrintable());</span><br><span class="line">System.out.println(<span class="string">"-------------------------------------------------------------------------------------------------------"</span>);</span><br><span class="line"></span><br><span class="line">String sin = builderString.intern();</span><br><span class="line">System.out.println(<span class="string">"-------------------------------------------------------------------------------------------------------"</span>);</span><br><span class="line">System.out.println(<span class="string">"init builderString.intern() info"</span>);</span><br><span class="line">System.out.println(GraphLayout.parseInstance(sin).toPrintable());</span><br><span class="line">System.out.println(<span class="string">"-------------------------------------------------------------------------------------------------------"</span>);</span><br><span class="line"></span><br><span class="line">String constStr = <span class="string">"faker大魔王"</span>;</span><br><span class="line">System.out.println(<span class="string">"-------------------------------------------------------------------------------------------------------"</span>);</span><br><span class="line">System.out.println(<span class="string">"init String constStr = 'faker大魔王' info"</span>);</span><br><span class="line">System.out.println(GraphLayout.parseInstance(constStr).toPrintable());</span><br><span class="line">System.out.println(<span class="string">"-------------------------------------------------------------------------------------------------------"</span>);</span><br><span class="line"></span><br><span class="line">String newString = new String(<span class="string">"faker大魔王"</span>);</span><br><span class="line">System.out.println(<span class="string">"-------------------------------------------------------------------------------------------------------"</span>);</span><br><span class="line">System.out.println(<span class="string">"init new String('faker大魔王') info"</span>);</span><br><span class="line">System.out.println(GraphLayout.parseInstance(newString).toPrintable());</span><br><span class="line">System.out.println(<span class="string">"-------------------------------------------------------------------------------------------------------"</span>);</span><br><span class="line"></span><br><span class="line">String newString2 = new String(<span class="string">"faker大魔王"</span>);</span><br><span class="line">System.out.println(<span class="string">"-------------------------------------------------------------------------------------------------------"</span>);</span><br><span class="line">System.out.println(<span class="string">"init new String('faker大魔王') 2 info"</span>);</span><br><span class="line">System.out.println(GraphLayout.parseInstance(newString2).toPrintable());</span><br><span class="line">System.out.println(<span class="string">"-------------------------------------------------------------------------------------------------------"</span>);</span><br><span class="line"></span><br><span class="line">String newStringConcatString = new String(<span class="string">"faker"</span>)+<span class="string">"大魔王"</span>;</span><br><span class="line">System.out.println(<span class="string">"-------------------------------------------------------------------------------------------------------"</span>);</span><br><span class="line">System.out.println(<span class="string">"init String newStringConcatString = new String('faker')+'大魔王' info"</span>);</span><br><span class="line">System.out.println(GraphLayout.parseInstance(newStringConcatString).toPrintable());</span><br><span class="line">System.out.println(<span class="string">"-------------------------------------------------------------------------------------------------------"</span>);</span><br><span class="line"></span><br><span class="line">String newStringConcatString2 = new String(<span class="string">"faker"</span>)+new String(<span class="string">"大魔王"</span>);</span><br><span class="line">System.out.println(<span class="string">"-------------------------------------------------------------------------------------------------------"</span>);</span><br><span class="line">System.out.println(<span class="string">"init String newStringConcatString2 = new String('faker')+new String('大魔王') info"</span>);</span><br><span class="line">System.out.println(GraphLayout.parseInstance(newStringConcatString2).toPrintable());</span><br><span class="line">System.out.println(<span class="string">"-------------------------------------------------------------------------------------------------------"</span>);</span><br></pre></td></tr></table></figure>
<h3 id="输出结果—jdk1-6"><a href="#输出结果—jdk1-6" class="headerlink" title="输出结果—jdk1.6"></a>输出结果—jdk1.6</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br></pre></td><td class="code"><pre><span class="line"><span class="literal">false</span></span><br><span class="line"><span class="literal">false</span></span><br><span class="line">use jol check ...</span><br><span class="line">-------------------------------------------------------------------------------------------------------</span><br><span class="line">builderString info</span><br><span class="line">java.lang.String@1b17a8bdd object externals:</span><br><span class="line">          ADDRESS       SIZE TYPE             PATH                           VALUE</span><br><span class="line">        7d5efcbe0         32 java.lang.String                                (object)</span><br><span class="line">        7d5efcc00         32 [C               .value                         [f, a, k, e, r, 大, 魔, 王]</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">-------------------------------------------------------------------------------------------------------</span><br><span class="line">-------------------------------------------------------------------------------------------------------</span><br><span class="line">init builderString.intern() info</span><br><span class="line">java.lang.String@60765a16d object externals:</span><br><span class="line">          ADDRESS       SIZE TYPE             PATH                           VALUE</span><br><span class="line">        77cfe3860         32 java.lang.String                                (object)</span><br><span class="line">        77cfe3880         32 [C               .value                         [f, a, k, e, r, 大, 魔, 王]</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">-------------------------------------------------------------------------------------------------------</span><br><span class="line">-------------------------------------------------------------------------------------------------------</span><br><span class="line">init String constStr = <span class="string">'faker大魔王'</span> info</span><br><span class="line">java.lang.String@60765a16d object externals:</span><br><span class="line">          ADDRESS       SIZE TYPE             PATH                           VALUE</span><br><span class="line">        77cfe3860         32 java.lang.String                                (object)</span><br><span class="line">        77cfe3880         32 [C               .value                         [f, a, k, e, r, 大, 魔, 王]</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">-------------------------------------------------------------------------------------------------------</span><br><span class="line">-------------------------------------------------------------------------------------------------------</span><br><span class="line">init new String(<span class="string">'faker大魔王'</span>) info</span><br><span class="line">java.lang.String@5ae80842d object externals:</span><br><span class="line">          ADDRESS       SIZE TYPE             PATH                           VALUE</span><br><span class="line">        77cfe3880         32 [C               .value                         [f, a, k, e, r, 大, 魔, 王]</span><br><span class="line">        77cfe38a0 1498006336 (something <span class="keyword">else</span>) (somewhere <span class="keyword">else</span>)               (something <span class="keyword">else</span>)</span><br><span class="line">        7d647fbe0         32 java.lang.String                                (object)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">-------------------------------------------------------------------------------------------------------</span><br><span class="line">-------------------------------------------------------------------------------------------------------</span><br><span class="line">init new String(<span class="string">'faker大魔王'</span>) 2 info</span><br><span class="line">java.lang.String@377653aed object externals:</span><br><span class="line">          ADDRESS       SIZE TYPE             PATH                           VALUE</span><br><span class="line">        77cfe3880         32 [C               .value                         [f, a, k, e, r, 大, 魔, 王]</span><br><span class="line">        77cfe38a0 1498033856 (something <span class="keyword">else</span>) (somewhere <span class="keyword">else</span>)               (something <span class="keyword">else</span>)</span><br><span class="line">        7d6486760         32 java.lang.String                                (object)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">-------------------------------------------------------------------------------------------------------</span><br><span class="line">-------------------------------------------------------------------------------------------------------</span><br><span class="line">init String newStringConcatString = new String(<span class="string">'faker'</span>)+<span class="string">'大魔王'</span> info</span><br><span class="line">java.lang.String@396fe0f4d object externals:</span><br><span class="line">          ADDRESS       SIZE TYPE             PATH                           VALUE</span><br><span class="line">        7d648d358         32 java.lang.String                                (object)</span><br><span class="line">        7d648d378         32 [C               .value                         [f, a, k, e, r, 大, 魔, 王]</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">-------------------------------------------------------------------------------------------------------</span><br><span class="line">-------------------------------------------------------------------------------------------------------</span><br><span class="line">init String newStringConcatString2 = new String(<span class="string">'faker'</span>)+new String(<span class="string">'大魔王'</span>) info</span><br><span class="line">java.lang.String@3ed02b51d object externals:</span><br><span class="line">          ADDRESS       SIZE TYPE             PATH                           VALUE</span><br><span class="line">        7d6492950         32 java.lang.String                                (object)</span><br><span class="line">        7d6492970         32 [C               .value                         [f, a, k, e, r, 大, 魔, 王]</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">-------------------------------------------------------------------------------------------------------</span><br></pre></td></tr></table></figure>
<h3 id="输出结果—jdk1-8"><a href="#输出结果—jdk1-8" class="headerlink" title="输出结果—jdk1.8"></a>输出结果—jdk1.8</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br></pre></td><td class="code"><pre><span class="line"><span class="literal">true</span></span><br><span class="line"><span class="literal">false</span></span><br><span class="line">use jol check ...</span><br><span class="line">-------------------------------------------------------------------------------------------------------</span><br><span class="line">builderString info</span><br><span class="line">java.lang.String@1540e19dd object externals:</span><br><span class="line">          ADDRESS       SIZE TYPE             PATH                           VALUE</span><br><span class="line">         d5ff44f8         24 java.lang.String                                (object)</span><br><span class="line">         d5ff4510         32 [C               .value                         [f, a, k, e, r, 大, 魔, 王]</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">-------------------------------------------------------------------------------------------------------</span><br><span class="line">-------------------------------------------------------------------------------------------------------</span><br><span class="line">init builderString.intern() info</span><br><span class="line">java.lang.String@1540e19dd object externals:</span><br><span class="line">          ADDRESS       SIZE TYPE             PATH                           VALUE</span><br><span class="line">         d5ff44f8         24 java.lang.String                                (object)</span><br><span class="line">         d5ff4510         32 [C               .value                         [f, a, k, e, r, 大, 魔, 王]</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">-------------------------------------------------------------------------------------------------------</span><br><span class="line">-------------------------------------------------------------------------------------------------------</span><br><span class="line">init String constStr = <span class="string">'faker大魔王'</span> info</span><br><span class="line">java.lang.String@1540e19dd object externals:</span><br><span class="line">          ADDRESS       SIZE TYPE             PATH                           VALUE</span><br><span class="line">         d5ff44f8         24 java.lang.String                                (object)</span><br><span class="line">         d5ff4510         32 [C               .value                         [f, a, k, e, r, 大, 魔, 王]</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">-------------------------------------------------------------------------------------------------------</span><br><span class="line">-------------------------------------------------------------------------------------------------------</span><br><span class="line">init new String(<span class="string">'faker大魔王'</span>) info</span><br><span class="line">java.lang.String@51521cc1d object externals:</span><br><span class="line">          ADDRESS       SIZE TYPE             PATH                           VALUE</span><br><span class="line">         d5ff4510         32 [C               .value                         [f, a, k, e, r, 大, 魔, 王]</span><br><span class="line">         d5ff4530    8779704 (something <span class="keyword">else</span>) (somewhere <span class="keyword">else</span>)               (something <span class="keyword">else</span>)</span><br><span class="line">         d6853ce8         24 java.lang.String                                (object)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">-------------------------------------------------------------------------------------------------------</span><br><span class="line">-------------------------------------------------------------------------------------------------------</span><br><span class="line">init new String(<span class="string">'faker大魔王'</span>) 2 info</span><br><span class="line">java.lang.String@1b4fb997d object externals:</span><br><span class="line">          ADDRESS       SIZE TYPE             PATH                           VALUE</span><br><span class="line">         d5ff4510         32 [C               .value                         [f, a, k, e, r, 大, 魔, 王]</span><br><span class="line">         d5ff4530    8805504 (something <span class="keyword">else</span>) (somewhere <span class="keyword">else</span>)               (something <span class="keyword">else</span>)</span><br><span class="line">         d685a1b0         24 java.lang.String                                (object)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">-------------------------------------------------------------------------------------------------------</span><br><span class="line">-------------------------------------------------------------------------------------------------------</span><br><span class="line">init String newStringConcatString = new String(<span class="string">'faker'</span>)+<span class="string">'大魔王'</span> info</span><br><span class="line">java.lang.String@deb6432d object externals:</span><br><span class="line">          ADDRESS       SIZE TYPE             PATH                           VALUE</span><br><span class="line">         d6860660         24 java.lang.String                                (object)</span><br><span class="line">         d6860678         32 [C               .value                         [f, a, k, e, r, 大, 魔, 王]</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">-------------------------------------------------------------------------------------------------------</span><br><span class="line">-------------------------------------------------------------------------------------------------------</span><br><span class="line">init String newStringConcatString2 = new String(<span class="string">'faker'</span>)+new String(<span class="string">'大魔王'</span>) info</span><br><span class="line">java.lang.String@694f9431d object externals:</span><br><span class="line">          ADDRESS       SIZE TYPE             PATH                           VALUE</span><br><span class="line">         d6865708         24 java.lang.String                                (object)</span><br><span class="line">         d6865720         32 [C               .value                         [f, a, k, e, r, 大, 魔, 王]</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">-------------------------------------------------------------------------------------------------------</span><br></pre></td></tr></table></figure>
<h2 id="String、StringBuffer、StringBuilder"><a href="#String、StringBuffer、StringBuilder" class="headerlink" title="String、StringBuffer、StringBuilder"></a>String、StringBuffer、StringBuilder</h2><p>StringBuffer是StringBuilder线程安全版本的实现<br>所以以下着重讲StringBuilder为什么拼接会比String快，同时节约内存<br>以及为什么在字符串很短以及拼接次数少时，两者效率差距不大而到了次数多时，差距会变化很大</p>
<p>String中的拼接方法<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">   void getChars(char dst[], int dstBegin) &#123;</span><br><span class="line">       System.arraycopy(value, 0, dst, dstBegin, value.length);</span><br><span class="line">   &#125;</span><br><span class="line">   public String concat(String str) &#123;</span><br><span class="line">       int otherLen = str.length();</span><br><span class="line">       <span class="keyword">if</span> (otherLen == 0) &#123;</span><br><span class="line">           <span class="built_in">return</span> this;</span><br><span class="line">       &#125;</span><br><span class="line">       int len = value.length;</span><br><span class="line">       char buf[] = Arrays.copyOf(value, len + otherLen);</span><br><span class="line">       str.getChars(buf, len);</span><br><span class="line">       <span class="built_in">return</span> new String(buf, <span class="literal">true</span>);</span><br><span class="line">   &#125;</span><br><span class="line">/*</span><br><span class="line">   * Package private constructor <span class="built_in">which</span> shares value array <span class="keyword">for</span> speed.</span><br><span class="line">   * this constructor is always expected to be called with share==<span class="literal">true</span>.</span><br><span class="line">   * a separate constructor is needed because we already have a public</span><br><span class="line">   * String(char[]) constructor that makes a copy of the given char[].</span><br><span class="line">   */</span><br><span class="line">   String(char[] value, boolean share) &#123;</span><br><span class="line">       // assert share : <span class="string">"unshared not supported"</span>;</span><br><span class="line">       this.value = value;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure></p>
<p>也就是每一次拼接的流程是创建一个长度刚好可以容纳这个拼接后的字符串的新数组，把两者字符复制进去<br>再来看看StringBuilder的实现<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">   public AbstractStringBuilder append(String str) &#123;</span><br><span class="line">       <span class="keyword">if</span> (str == null)</span><br><span class="line">           <span class="built_in">return</span> appendNull();</span><br><span class="line">       int len = str.length();</span><br><span class="line">       ensureCapacityInternal(count + len);</span><br><span class="line">       str.getChars(0, len, value, count);</span><br><span class="line">       count += len;</span><br><span class="line">       <span class="built_in">return</span> this;</span><br><span class="line">   &#125;</span><br><span class="line">private void ensureCapacityInternal(int minimumCapacity) &#123;</span><br><span class="line">       // overflow-conscious code</span><br><span class="line">       <span class="keyword">if</span> (minimumCapacity - value.length &gt; 0) &#123;</span><br><span class="line">           value = Arrays.copyOf(value,</span><br><span class="line">                   newCapacity(minimumCapacity));</span><br><span class="line">       &#125;</span><br><span class="line">   &#125;</span><br><span class="line">private int newCapacity(int minCapacity) &#123;</span><br><span class="line">       // overflow-conscious code</span><br><span class="line">       int newCapacity = (value.length &lt;&lt; 1) + 2;</span><br><span class="line">       <span class="keyword">if</span> (newCapacity - minCapacity &lt; 0) &#123;</span><br><span class="line">           newCapacity = minCapacity;</span><br><span class="line">       &#125;</span><br><span class="line">       <span class="built_in">return</span> (newCapacity &lt;= 0 || MAX_ARRAY_SIZE - newCapacity &lt; 0)</span><br><span class="line">           ? hugeCapacity(minCapacity)</span><br><span class="line">           : newCapacity;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure></p>
<p>StringBuilder和String一样在内部维护一个字符数组，但是StringBuilder在构造时会多预留16个位置<br>StringBuilder会调用父类AbstractStringBuilder的append方法<br>具体操作为如果当前数组长度不够存储，则将数组长度扩展为原来的两倍+2，如果扩展后还是不够，再直接一次性扩展到刚好满足<br>这意味着如果每次拼接的字符串相对当前字符串数组要小的多时，因为每次扩容是倍数增长，所以扩容次数相比String会减少<br>同时直接操作数组除了创建新数组没有创建别的对象，性能也更好(String的内部数组是final不可变，所以每次拼接都是创建新的String对象以及数组对象)<br>从这里也可以看出，如果每次拼接的字符串长度是指数增长，都要接近甚至更高于数组最新的长度，那么StringBuilder拼接的效率也会下降到和String差不多（当然这种场景是极少见的）</p>
<h3 id="请移步"><a href="#请移步" class="headerlink" title="请移步"></a>请移步</h3><p>个人主页: <a href="http://yangyitao.top" target="_blank" rel="noopener">yangyitao.top</a></p>

      
    </div>
    
  </div>
  
    
<nav id="article-nav">
  
    <a href="/blog/2019/05/26/使用HandlerInterceptor和RateLimiter进行限流/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">&lt;</strong>
      <div class="article-nav-title">
        
          使用HandlerInterceptor和RateLimiter进行限流
        
      </div>
    </a>
  
  
    <a href="/blog/2019/04/07/动态代理与静态代理/" id="article-nav-older" class="article-nav-link-wrap">
      <div class="article-nav-title">动态代理与静态代理</div>
      <strong class="article-nav-caption">&gt;</strong>
    </a>
  
</nav>

  
</article>


<div class="ds-share share" data-thread-key="字符串常量池在1.6与1.8以及String、StringBuffer、StringBuilder" data-title="字符串常量池在1.6与1.8以及String、StringBuffer、StringBuilder" data-url="http://eetal.gitee.io/blog/blog/2019/04/12/字符串常量池在1.6与1.8以及String、StringBuffer、StringBuilder/"  data-images="/blog/images/head.jpg" data-content="字符串常量池在1.6与1.8以及String、StringBuffer、StringBuilder">
    <div class="ds-share-inline">
      <ul  class="ds-share-icons-16">
      	<li data-toggle="ds-share-icons-more"><a class="ds-more" href="javascript:void(0);">分享到：</a></li>
        <li><a class="ds-weibo" href="javascript:void(0);" data-service="weibo">微博</a></li>
        <li><a class="ds-qzone" href="javascript:void(0);" data-service="qzone">QQ空间</a></li>
        <li><a class="ds-qqt" href="javascript:void(0);" data-service="qqt">腾讯微博</a></li>
        <li><a class="ds-wechat" href="javascript:void(0);" data-service="wechat">微信</a></li>
      </ul>
      <div class="ds-share-icons-more">
      </div>
    </div>
 </div>
 





</div>
      <footer id="footer">
  <div class="outer">
    <div id="footer-info">
      <div class="footer-left">
        &copy; 2019 Eetal
      </div>
        <div class="footer-right">
          <a href="http://hexo.io/" target="_blank">Hexo</a>  Theme <a href="https://github.com/smackgg/hexo-theme-smackdown" target="_blank">Smackdown</a>
        </div>
    </div>
  </div>
</footer>
    </div>
    
  <link rel="stylesheet" href="/blog/fancybox/jquery.fancybox.css">


<script>
	var yiliaConfig = {
		fancybox: true,
		mathjax: true,
		animate: true,
		isHome: false,
		isPost: true,
		isArchive: false,
		isTag: false,
		isCategory: false,
		open_in_new: false
	}
</script>
<script src="/blog/js/main.js"></script>



<script type="text/x-mathjax-config">
MathJax.Hub.Config({
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    }
});

MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for(i=0; i < all.length; i += 1) {
        all[i].SourceElement().parentNode.className += ' has-jax';                 
    }       
});
</script>

<script src="//cdn.bootcss.com/mathjax/2.7.0/MathJax.js"></script>


  </div>
</body>
</html>